<template>
  <div>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="供应商编号">
        <el-input v-model="formInline.venDorCode" placeholder="供应商编号" clearable />
      </el-form-item>
      <el-form-item label="供应商名称">
        <el-input v-model="formInline.vendorName" placeholder="供应商名称" clearable />
      </el-form-item>
      <el-form-item label="负责人电话">
        <el-input v-model="formInline.responsiblePhone" placeholder="负责人电话" clearable />
      </el-form-item>
      <el-form-item label="所属市场">
        <el-select v-model="formInline.markets" placeholder="所属市场" style="width: 120px" clearable>
          <el-option label="玉林市犀浦镇牛羊市场" value="玉林市犀浦镇牛羊市场" />
          <el-option label="贺州市龙州县牛羊市场" value="贺州市龙州县牛羊市场" />
        </el-select>
      </el-form-item>
      <el-form-item label="服务人员">
        <el-select v-model="formInline.salesman" placeholder="服务人员" style="width: 120px" clearable>
          <el-option label="刘永刚" value="刘永刚" />
          <el-option label="孟盘龙" value="孟盘龙" />
          <el-option label="赵秋实" value="赵秋实" />
          <el-option label="牛骞若" value="牛骞若" />
          <el-option label="赵思彤" value="赵思彤" />
          <el-option label="于晋哲" value="于晋哲" />
        </el-select>
      </el-form-item>
      <el-form-item label="使用状态">
        <el-select v-model="formInline.useState" placeholder="使用状态" style="width: 120px" clearable>
          <el-option label="启用" :value="true" />
          <el-option label="禁用" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getVendorList()">查询</el-button>
        <el-button type="primary" @click="addSuppliers()">添加</el-button>
        <el-button type="primary" @click="pDel()">批量删除</el-button>
        <el-button type="danger" @click="ExportCustomer()">导出</el-button>
        <el-upload ref="uploadRef" class="upload-demo" action="https://localhost:62593/api/VendorModel/ImportCustomer"
          :auto-upload="true" show-file-list="true" :before-upload="beforeUpload" :on-success="handleSuccess"
          :on-error="handleError" style="margin-top: 10px;margin-left: 14px;">
          <template #trigger>
            <el-button type="info">导入</el-button>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <div class="app-container">
      <div class="search-container">
        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="venDorCode" label="供应商编号" />
          <el-table-column prop="vendorName" label="供应商名称" />
          <el-table-column prop="vendorType" label="供应商类型" />
          <el-table-column prop="responsiblePhone" label="负责人电话" />
          <el-table-column prop="businessId" label="录入单位">
            <template v-slot="scope">
              {{ scope.row.businessId == 1 ? '总部' : scope.row.businessId == 2 ? '分公司' : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="unitsOfReference" label="使用单位" />
          <el-table-column prop="markets" label="所属市场" />
          <el-table-column prop="salesman" label="服务人员" />
          <el-table-column prop="useState" label="使用状态">
            <template #default="scope">
              <el-tag type="primary" v-if="scope.row.useState == 1">启用</el-tag>
              <el-tag type="danger" v-else>禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createBy" label="修改人">
            <template v-slot="scope">
              {{ scope.row.createBy == 1 ? 'admin' : '李四' }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="修改时间" />
          <el-table-column fixed="right" label="操作" align="center" width="200px">
            <template #default="scope">
              <el-button link type="danger" size="small" @click="dels(scope.row.vendorSnowId)">删除</el-button>
              <el-button link type="primairy" size="small" @click="editSupplier(scope.row.vendorSnowId)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="formInline.pageIndex" v-model:page-size="formInline.pageSize"
          :page-sizes="[1, 2, 3, 4]" :background="true" layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        <el-dialog v-model="dialogVisible" title="Tips" width="500" :before-close="handleClose">
          <addSupplier />
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogVisible = false">Cancel</el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import purcure from '@/api/PurchaseMent/index'
import { purcoreQuery, buildingIdQuery } from '@/api/PurchaseMent/model'
import vendor from '@/api/VendorMangMent/index'
import { vendorQuery } from '@/api/VendorMangMent/model'
import { ElMessage, ElMessageBox } from 'element-plus'
import addSupplier from './addSupplier.vue'
import * as XLSX from 'xlsx' // Vue3 版本
import { UploadInstance } from "element-plus";
//参数
const formInline = reactive<vendorQuery>({
  venDorCode: "",
  vendorName: "",
  responsiblePhone: "",
  markets: "",
  salesman: "",
  useState: true,
  pageIndex: 1,
  pageSize: 15
})
//数据显示
//总条数
const totalCount = ref()
const pageCount = ref()
const tableData: any = ref([])
const getVendorList = () => {
  vendor.getList(formInline).then((res: any) => {
    console.log('完整响应数据:', res);
    tableData.value = res.data.data
    totalCount.value = res.data.totalCount
    pageCount.value = res.data.pageCount
  })
}
onMounted(() => {
  getVendorList()
})
//分页
const handleSizeChange = (val: number) => {
  formInline.pageSize = val
  getVendorList()
}
const handleCurrentChange = (val: number) => {
  formInline.pageIndex = val
  getVendorList()
}
//删除
const dels = (id: any) => {
  const ids = [id];
  console.log(ids)
  ElMessageBox.confirm(
    '确认要删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    vendor.deletes(ids).then((res: any) => {
      if (res.code > 0) {
        ElMessage.success('删除成功');
        getVendorList();
      }
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '删除已取消',
    });
  });
};

//导出
const ExportCustomer = () => {
  location.href = `https://localhost:62593/api/VendorModel/ExportCustomer?
venDorCode	=${formInline.venDorCode}
&vendorName=${formInline.vendorName}
&responsiblePhone=${formInline.responsiblePhone}
&markets=${formInline.markets}
&salesman=${formInline.salesman}
&useState=${formInline.useState}
&PageIndex=${formInline.pageIndex}
&PageSize=${formInline.pageSize}
`;
};
const multipleSelection = ref([])
//批量删除
const handleSelectionChange = (val: any) => {
  val.forEach(element => {
    multipleSelection.value.push(element.vendorSnowId)
  });
}
//批量删除
const pDel = () => {
  ElMessageBox.confirm(
    '确认要删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    vendor.deletes(multipleSelection.value).then((res: any) => {
      if (res.code > 0) {
        ElMessage.success('删除成功');
        getVendorList();
      }
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '删除已取消',
    });
  });
};
//导入

const uploadRef = ref<UploadInstance | null>(null);

const beforeUpload = (file: File) => {
  const isExcel =
    file.type === 'application/vnd.ms-excel' ||
    file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件!');
  }
  return isExcel;
};

const handleSuccess = (response: any, file: File, fileList: File[]) => {
  console.log('上传成功', response, file, fileList);
  ElMessage.success('文件上传成功!');

  // 清除上传的文件
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
  // 刷新表格数据（这里用 console.log 模拟刷新表格数据）
  console.log('刷新表格数据...');
};

const handleError = (err: any, file: File, fileList: File[]) => {
  console.log('上传失败', err, file, fileList);
  ElMessage.error('文件上传失败!');
};
//弹框添加
const dialogVisible = ref(false)
const add = () => {
  dialogVisible.value = true
}
//查看
import { useRouter } from 'vue-router'
const router = useRouter()

const editSupplier = (vendorSnowId: any) => {
  router.push({
    path: "/editSupplier",
    query: {
      vendorSnowId: vendorSnowId,
    },
  });
};
//添加
const addSuppliers = () => {
  router.push('/addSupplier')
}
</script>